import {Injectable} from '@angular/core';
import {Interceptor, InterceptedRequest, InterceptedResponse} from 'ng2-interceptors';
import {AuthService} from './../user/auth.service';

@Injectable()
export class HttpInterceptor implements Interceptor {
  constructor(private authService: AuthService) {
  }

  public interceptBefore(request: InterceptedRequest): InterceptedRequest {
    request.options.headers.set('token', this.authService.getTokenId() ? this.authService.getTokenId() : ' ');
    console.log('req', request);
    return request;
  }

  public interceptAfter(response: InterceptedResponse): InterceptedResponse {
    console.log('res', response);
    const body = response.response.json();
    if (body.status === '2') { // Token失效
      this.authService.sendLoginStatus(false);
    }
    return response;
  }

}
